<template>
  <div>
    <h4>案例-求和</h4>
    <hr />

    <Sum :n="sum" />

    <Ipt @add="sum++" @sub="sum--" @getNum="fn" />

    <But @oddAdd="add01" @timeoutAdd="add02" />
  </div>
</template>

<script>
import Sum from '../components/Sum.vue'
import Ipt from '../components/Ipt.vue'
import But from '../components/But.vue'

export default {
  data() {
    return {
      sum: 0,
      num: 0
    }
  },
  methods: {
    // 当前和为奇数的时候再累加
    add01() {
      // 下拉框中选择的数值会变成字符串
      if (this.sum % 2 === 1) this.sum += this.num
    },
    // 等2秒钟再累加
    add02() {
      // 涉及到this的指向，必须使用箭头函数
      setTimeout(() => {
        this.sum += this.num
      }, 2000)
    },

    fn(n) {
      // 隐式转换为数值
      this.num = n - 0
    }
  },
  components: {
    Sum,
    Ipt,
    But
  }
}
</script>

<style lang="less" scoped></style>
